package io.binghe.seckill.infrastructure.shiro;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.binghe.seckill.domain.constans.SeckillConstants;

import java.util.Date;

/**
 * @author: Dragon
 * @since: 2024/1/14 11:47
 */
public class JwtUtils {

    public static boolean verify(String token, String secret) {

        /**
         * 检验token是否正确
         */
        try{
            //更具密码生产JWT校验器
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier jwtVerifier = JWT.require(algorithm)
                    .withClaim(SeckillConstants.TOKEN_CLAIM,
                            getUserId(token)).build();

            jwtVerifier.verify(token);

            return true;
        } catch (JWTVerificationException exception) {
            return false;
        }
    }

    /**
     * 获取token中的信息，无需secret解密也能获得
     * @param token
     * @return
     */
    public static Long getUserId(String token) {

        try{
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(SeckillConstants.TOKEN_CLAIM).asLong();

        } catch (JWTDecodeException e) {
            return null;
        }

    }

    /**
     *
     * @param userId 用户名
     * @param secret 制作此token的签名依据
     * @return
     */
    public static String sign(Long userId, String secret) {
        Date date = new Date(System.currentTimeMillis() + SeckillConstants.TOKEN_EXPIRE_TIME);

        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create()
                .withClaim(SeckillConstants.TOKEN_CLAIM, userId)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    public static String sign(Long userId) {
        return sign(userId, SeckillConstants.JWT_SECRET);
    }
}
